import 'package:aio/aio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/http/bean/works_2023/report_loss_bean.dart';
import 'package:app/src/http/bean/wroks/order_item_info.dart';
import 'package:app/src/http/bean/wroks/pay_free.dart';
import 'package:app/src/http/bean/wroks/pay_notice_bean.dart';
import 'package:app/src/http/bean/wroks/product_bean.dart';
import 'package:app/src/http/bean/wroks/receipt_bean.dart';
import 'package:app/src/http/bean/wroks/special_clauses.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/route/works/public/items/ui_base.dart';
import 'package:app/src/ui/route/works/public/items/ui_card.dart';
import 'package:app/src/utils/a_combined_utils.dart';
import 'package:app/src/utils/image_path_utils.dart';

import '../../../../../http/bean/wroks/payfree_return_bean.dart';
import '../../../../app_ui.dart';

///报损审核：报损补片
class UiReportLossAdapter1 {
  static Widget build(BuildContext context, FLoseApplyInfoBean? data,
      List<LoseApplyDetailN6081Bean>? datas,
      {String? title}) {
    if (StringUtils.isEmpty(datas)) {
      return AppUi.getEmptyView();
    }
    List<Widget> children = [];
    if (StringUtils.isEmpty(title)) {
      title = AppStrings.of(context).BaosunBupian; //报损补片
    }
    children.add(
        UiBase.title(context, title, bottom: AppEdgeInsets.margin_bottom)); //标题
    children.add(_table(
      context,
      data,
      datas,
    ));
    var column = UiBase.column(context, children);
    var card = UiCard.build(context, column);
    return card;
  }

  static Widget _table(
    BuildContext context,
    FLoseApplyInfoBean? data,
    List<LoseApplyDetailN6081Bean>? datas,
  ) {
    return StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
        List<TableRow> children = [];
        //==========================================================================标题
        children.add(TableRow(
            //第一行，添加背景色
            decoration:
                BoxDecoration(color: AppColors.backgroundColorWithTableTitle),
            children: _titles(context)));
        if (datas != null && datas.length > 0) {
          var postion = 1;
          datas.forEach((element) {
            //======================================================================内容
            var cells = _contents(context, postion, data, element, setState);
            postion++;
            children.add(TableRow(children: cells));
            if (element.isOpenAn()) {
              //二级详情，标题
              children.add(TableRow(
                  decoration: BoxDecoration(
                      color: AppColors.backgroundColorWithTabelSecondary),
                  children: _titles2(context)));
              // //二级详情，内容
              var data = element;
              var postion2 = 1;
              element.mList?.forEach((element) {
                var secondaryContents = _secondaryContents(
                    context, postion2, element, data, setState);
                postion2++;
                children.add(TableRow(children: secondaryContents));
              });
            }
          });
        }
        var table = Table(
          defaultVerticalAlignment: TableCellVerticalAlignment.middle,
          columnWidths: {
            0: FixedColumnWidth(50),
            1: FixedColumnWidth(150),
            2: FixedColumnWidth(200),
            3: FixedColumnWidth(300),
            4: FixedColumnWidth(200),
          },
          textDirection: TextDirection.ltr,
          border: AppStyle.getTableBorder(),
          children: children,
        );
        var width = 2000.0;
        if (width < px.screenWidth()) {
          width = px.screenWidth();
        }
        return SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          physics: BouncingScrollPhysics(),
          child: Container(
            width: width,
            child: table,
          ),
        );
      },
    );
  }

  ///标题
  static List<Widget> _titles(BuildContext context) {
    List<Widget> children = [];
    children.add(_addItem(AppStrings.of(context).TheSerial)); //序号
    children.add(_addItem(AppStrings.of(context).OrderCode2)); //任务单号
    children.add(_addItem(AppStrings.of(context).StockInCode)); //入库单号
    children.add(_addItem(AppStrings.of(context).ProductName)); //产品名称
    children.add(_addItem(AppStrings.of(context).ItemWidth)); //宽
    children.add(_addItem(AppStrings.of(context).ItemHeight)); //高
    children.add(_addItem(AppStrings.of(context).ItemCode)); //安装编号
    children.add(_addItem(AppStrings.of(context).ReturnNum)); //退货数量
    children.add(_addItem(AppStrings.of(context).WasteNum)); //报废数量
    children.add(_addItem(AppStrings.of(context).CPNum)); //拆片数量
    children.add(_addItem(AppStrings.of(context).BackNum)); //退库数量(自动)
    children.add(_addItem(AppStrings.of(context).GroupList)); //操作班组
    return children;
  }

  ///内容
  static List<Widget> _contents(
      BuildContext context,
      int postion,
      FLoseApplyInfoBean? data,
      LoseApplyDetailN6081Bean element,
      StateSetter setState) {
    List<Widget> children = [];
    children.add(_addItem((postion).toString())); //序号
    children.add(_addItem(element.OrderCode)); //任务单号
    children.add(_addItem(element.StockInCode)); //入库单号
    children.add(_addItem(element.ProductName)); //产品名称
    children.add(_addItem(element.ItemWidth)); //宽
    children.add(_addItem(element.ItemHeight)); //高
    children.add(_addItem(element.ItemCode)); //安装编号
    children.add(_addItem(element.Num)); //退货数量
    children.add(_addItem(element.WasteNum, isBlue: true, onTap: () {
      try {
        var max = element.getTHNum();
        if (max > 0) {
          List<RollerBean> rollers = [];
          for (int i = 0; i <= max; i++) {
            RollerBean rollerBean = RollerBean();
            rollerBean.key = i.toString();
            rollerBean.value = i.toString();
            rollers.add(rollerBean);
          }
          var key = element.WasteNum;
          AppDialog.showDialogWithRollerPicker(context,
                  datas: rollers, key: key)
              ?.then((value) => {
                    setState(() {
                      if (value != null && key != value?.key) {
                        element.WasteNum = value.value; //报废数量
                        try {
                          var cp =
                              element.getTHNum() - element.getWasteNum(); //拆片数量
                          if (element.getCPNum() > cp) {
                            element.CPNum = "0";
                            element
                                .initList(); //fixme ================================拆片数据
                          }
                          element.getBackNumStr(); //退库数量
                        } catch (e) {}
                      }
                    })
                  });
        }
      } catch (e) {}
    })); //报废数量
    children.add(_addItem(element.CPNum, isBlue: true, onTap: () {
      try {
        var max = element.getTHNum();
        //拆片数量，拆片数据不能为空。
        if (max > 0) {
          if (StringUtils.isEmpty(element.mList)) {
            //该行玻璃不可以拆片
            Toast.showInfo(AppStrings.of(context).CPNumMsg, context);
            return;
          }
          List<RollerBean> rollers = [];
          for (int i = 0; i <= max; i++) {
            RollerBean rollerBean = RollerBean();
            rollerBean.key = i.toString();
            rollerBean.value = i.toString();
            rollers.add(rollerBean);
          }
          var key = element.CPNum;
          AppDialog.showDialogWithRollerPicker(context,
                  datas: rollers, key: key)
              ?.then((value) => {
                    setState(() {
                      if (value != null && key != value?.key) {
                        element.CPNum = value.value; //拆片数量
                        element.initList(); //拆片数据
                        try {
                          var wn =
                              element.getTHNum() - element.getCPNum(); //报废数量
                          if (element.getWasteNum() > wn) {
                            element.WasteNum = "0";
                          }
                          element.getBackNumStr(); //退库数量
                        } catch (e) {}
                      }
                    })
                  });
        }
      } catch (e) {}
    })); //拆片数量
    children.add(_addItem(element.getBackNumStr())); //退库数量(自动)
    children.add(_addItem(element.GroupName,
        hint: AppStrings.of(context).ClickSelect, isBlue: true, onTap: () {
      var MsgGroup = data?.GroupList;
      //List<GroupInfoBean>? MsgGroup2 = [];
      //不用加空白，里面自带了一共空白的
      // if (MsgGroup != null) {
      //   MsgGroup2?.add(GroupInfoBean()); //添加一个空白的
      //   MsgGroup2?.addAll(MsgGroup);
      // }
      var GroupId = element.GroupId;
      AppDialog.showDialogWithRollerPicker(context,
              datas: MsgGroup, key: GroupId)
          ?.then((value) {
        setState(() {
          if (value != null && element.GroupId != value?.GroupId) {
            //选中班组
            element.GroupId = value?.GroupId;
            element.GroupName = value?.GroupName;
          }
        });
      });
    })); //操作班组
    return children;
  }

  ///二级标题
  static List<Widget> _titles2(BuildContext context) {
    List<Widget> children = [];
    children.add(_addItem(""));
    children.add(_addItem(""));
    children.add(_addItem(""));
    children.add(_addItem(AppStrings.of(context).TheSerial)); //序号
    children.add(_addItem(AppStrings.of(context).LevelShelfId)); //架卡编号
    children.add(_addItem(AppStrings.of(context).ProductName3)); //拆分产品
    children.add(_addItem(AppStrings.of(context).OrderItem)); //条目
    children.add(_addItem(AppStrings.of(context).ItemWidth)); //宽
    children.add(_addItem(AppStrings.of(context).ItemHeight)); //高
    children.add(_addItem(AppStrings.of(context).CPNum3)); //拆出合格数量
    children.add(_addItem(""));
    children.add(_addItem(""));
    return children;
  }

  ///二级内容
  static List<Widget> _secondaryContents(
      BuildContext context,
      int postion,
      PayFreeGoodReturnChild element,
      LoseApplyDetailN6081Bean data,
      StateSetter setState) {
    List<Widget> children = [];
    children.add(_addItem(""));
    children.add(_addItem(""));
    children.add(_addItem(""));
    children.add(_addItem((postion).toString())); //序号
    children.add(_addItem(element.LevelShelfId)); //架卡编号
    children.add(_addItem(element.ProductName)); //拆分产品
    children.add(_addItem(element.OrderItem)); //条目
    children.add(_addItem(element.ItemWidth)); //宽
    children.add(_addItem(element.ItemHeight)); //高
    children.add(_addItem(element.CPNum, isBlue: true, onTap: () {
      try {
        var max = data.getCPNum();
        if (max > 0) {
          List<RollerBean> rollers = [];
          for (int i = 0; i <= max; i++) {
            RollerBean rollerBean = RollerBean();
            rollerBean.key = i.toString();
            rollerBean.value = i.toString();
            rollers.add(rollerBean);
          }
          var key = element.CPNum;
          AppDialog.showDialogWithRollerPicker(context,
                  datas: rollers, key: key)
              ?.then((value) => {
                    setState(() {
                      if (value != null && key != value?.key) {
                        element.CPNum = value.value; //可拆数量
                      }
                    })
                  });
        }
      } catch (e) {}
    })); //可拆数量
    children.add(_addItem(""));
    children.add(_addItem(""));
    return children;
  }

  static Widget _addItem(String? text,
      {bool isBlue = false, GestureTapCallback? onTap, String? hint}) {
    Widget child = Center(child: _text(text, isBlue: isBlue, hint: hint));
    if (onTap == null) {
      return child;
    }
    return InkWell(
      child: child,
      onTap: onTap,
    );
  }

  static Widget _text(String? text, {bool isBlue = false, String? hint}) {
    TextStyle? style = null;
    if (isBlue) {
      style = AppStyle.textStyleWithCardBlue();
    } else {
      style = AppStyle.textStyleWithCard();
    }
    var textStr = text?.trim() ?? "";
    if (StringUtils.isEmpty(textStr) && hint != null) {
      textStr = hint.trim();
    }
    return Text(
      textStr,
      style: style,
    );
  }
}
